package com.hanhai.zrb.api.biz.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.hanhai.common.util.MD5Util;
import com.hanhai.common.util.PageHelper;
import com.hanhai.zrb.api.biz.dao.mybatis.UserDao;
import com.hanhai.zrb.api.biz.service.CityInfoService;
import com.hanhai.zrb.api.biz.service.UserInfoService;
import com.hanhai.zrb.api.biz.service.UserService;
import com.hanhai.zrb.model.project.CityInfo;
import com.hanhai.zrb.model.user.User;
import com.hanhai.zrb.model.user.dto.UserSearchDto;
import com.hanhai.zrb.model.user.enums.UserInfoName;
import com.hanhai.zrb.model.user.vo.UserSearchVo;

@Service("userService")
public class UserServiceImpl implements UserService{

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Resource
	private UserDao userDao;
	@Resource
	private UserInfoService userInfoService;
	@Resource
	private CityInfoService cityInfoService;
	
	@Override
	public void updateMobile(User user) {
		userDao.updateModifyMobile(user);
	}
	
	public boolean saveUser(User user){
		try {
			userDao.save(user);
			return  true;
		} catch (Exception e) {
			logger.error("user create exception",e);
			return false;
		}
	}
	
	@Override
	public void updateOrg(User user){
		userDao.updateOrg(user);
	}
	
	@Override
	public void updatePassword(User user){
		//String temp = user.getPassword();
		//MD5Util.sha1(temp);
		user.setPassword(MD5Util.sha1(user.getPassword()));
		userDao.updateByPwd(user);
	}
	
	@Override
	public void updatePwdByMobile(String umobile,String inputPwd){
		User user = new User();
		user.setUmobile(umobile);
		user.setPassword(MD5Util.sha1(inputPwd));
		userDao.updatePwdByMobile(user);
	}
	
	
	@Override
	public User findById(Long id) {
		return userDao.findById(id);
	}

	@Override
	public void update(User user) {
		userDao.update(user);
	}

	@Override
	public User searchUser(String search) {
		User user = userDao.checkMobileOrEmailExist(search, null);
		if (user == null) {
			user = userDao.checkMobileOrEmailExist(null, search);
		}
		if (user != null) {
			user = userDao.findById(user.getUid());
		}
		
		//userDao.search(search);
		return user;
	}
	
	@Override
	public List<User> queryUserBySearch(String search){
		UserSearchDto userSearch = new UserSearchDto();
		if(StringUtils.isNotBlank(search)){
			userSearch.setKeyword("%"+search+"%");
		}
		userSearch.setKeyword("%"+search+"%");
		return userDao.listByKeyWord(userSearch);
	}
	
	@Override
	public PageInfo queryUserBySearch(String search,Integer pageNum,Integer pageSize){
		UserSearchDto userSearch = new UserSearchDto();
		if(StringUtils.isNotBlank(search)){
			userSearch.setKeyword("%"+search+"%");
		}
		PageHelper.startPage(pageNum, pageSize, true);
		List<User> list =userDao.findBySearch(userSearch);
		PageInfo pageInfo=new PageInfo(list);
		return pageInfo;
	}

	@Override
	public List<User> searchUserList(UserSearchDto userSearch) {
		if(null!=userSearch.getKeyword()){
			userSearch.setKeyword("%"+userSearch.getKeyword()+"%");
		}
		return userDao.findByKeyWord(userSearch);
	}
	
	@Override
	public PageInfo searchUserPage(UserSearchDto userSearch,Integer pageNum,Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize, true);
		List<User> list = searchUserList(userSearch);
		PageInfo pageInfo=new PageInfo(list);
		return pageInfo;
	}
	

	@Override
	public User findByUname(String uname) {
		return userDao.findByUname(uname);
	}

	@Override
	public User findByPhone(String mobilephone) {
		return userDao.findByPhone(mobilephone);
	}

	@Override
	public User findByEmail(String email) {
		return userDao.findByEmail(email);
	}

	@Override
	public void updateEmail(User user) {
		userDao.updateEmail(user);
	}
	
	/*@Override
	public PageInfo searchInvestorPage(UserSearchDto userSearch,int pageNum,int pageSize) {
		PageHelper.startPage(pageNum, pageSize, true);
		List<User> list = searchUserList(userSearch);
		if(null!=list&&list.size()>0){
			for(User user:list){
			   if(StringUtils.isBlank(user.getOrg())){
				   user.setMatchOrg(SystemConstants.Match_Org_Type.NAN.getCode());
			   }else{
				   List<Company> company = companyMapper.selectByNameExactly(user.getOrg());
				   int matchOrg = (null!=company&&company.size()>0)?SystemConstants.Match_Org_Type.MATCH.getCode():SystemConstants.Match_Org_Type.NOT_MATCH.getCode();
				   user.setMatchOrg(matchOrg);
			   }
			}
		}
		PageInfo pageInfo=new PageInfo(list);
		return pageInfo;
	}*/

	/*@Override
	public void authUser(User user) {
		InvestorOrg investorOrg = new InvestorOrg();
		investorOrg.setUserId(user.getUid());
		investorOrg.setOrgId(Integer.valueOf(user.getOrg()));
		investorOrgMapper.deleteByPrimaryKey(user.getUid());
		investorOrgMapper.insert(investorOrg);
		
		Company company = companyMapper.selectByPrimaryKey(Long.valueOf(user.getOrg()));
		User curUser =userDao.findById(user.getUid());
		
		user.setOrgId(company.getId());//回写投资人机构名称id
		user.setOrg(company.getName());//回写投资人机构名称
		if(curUser.getStatus()==11){//未认证状态,则设置认证时间和状态
			user.setAuthtime(new Date());
			user.setStatus(12);//设置状态为已认证
		}else{//否则,则设置更新时间
			user.setUptime(new Date());
		}
		userDao.update(user);
		
		//用户认证完毕后发送站内消息 目前只处理修改认证和认证两种情况的消息
		if(curUser.getStatus()==11||curUser.getStatus()==12){
			List<Long> receiverUids = new ArrayList<Long>();
		   	receiverUids.add(user.getUid());
		    //根据用户状态构造站内消息文本
			String content =curUser.getStatus()==11?MessageContentEnum.user_auth_succes_common.getMessage()+user.getOrg()+MessageContentEnum.user_auth_succes_investor.getMessage():MessageContentEnum.user_auth_modify_investor.getMessage()+curUser.getOrg()+MessageContentEnum.user_auth_modify_common1.getMessage()+user.getOrg()+MessageContentEnum.user_auth_modify_common2.getMessage();
		   	MessageBizType bizType = curUser.getStatus()==11?MessageBizType.user_auth_succes:MessageBizType.user_auth_modify;
		   	messageSendService.createNotifyMessage(receiverUids, content, bizType, "");
		}
	}
*/
	@Override
	public PageInfo queryUserBySearch(String search, Date beginTimes,
			Date endTimes, Integer status, Integer pageNum, Integer pageSize) {
		UserSearchDto userSearch = new UserSearchDto();
		userSearch.setUserType(2);
		if(StringUtils.isNotBlank(search)){
			userSearch.setKeyword("%"+search+"%");
		}

		userSearch.setStatus(status);
		userSearch.setStartTime(beginTimes);
		userSearch.setEndTime(endTimes);
		
		
		PageHelper.startPage(pageNum, pageSize, true);
		List<User> list =userDao.findByKeyWord(userSearch);
		PageInfo pageInfo=new PageInfo(list);
		return pageInfo;
	}

	@Override
	public List<User> findByOrgIdAndUserType(Long orgId,Integer type) {
		return userDao.findByOrgIdAndUserType(orgId,type);
	}

	@Override
	public List<User> findByUid(List<Long> userIdList) {
		if(CollectionUtils.isEmpty(userIdList)){
			return new ArrayList<User>();
		}
		List<User> list = userDao.findByUid(userIdList);
		//获得用户列表的时候，一般不需要密码
		if(list != null){
			for(User user:list){
				user.setPassword(null);
			}
		}
		return list;
	}

	@Override
	public PageInfo queryUserBySearchDto(UserSearchDto userSearch, Integer pageNum, Integer pageSize) {
		List<Long> uids = Lists.newArrayList();
		if (StringUtils.isNotBlank(userSearch.getProvince()) && !StringUtils.equals("0", userSearch.getProvince())) {
			// 判断查询是省还是查询的市
			if (StringUtils.isNotBlank(userSearch.getCity())) {
				 uids=userInfoService.queryUidsByLocation(userSearch.getCity());
			} else {
				 uids=userInfoService.queryUidsByLocation(userSearch.getProvince().substring(0,2));
			}
			if (CollectionUtils.isNotEmpty(uids)) {
				userSearch.setUids(uids);
			}else{
				return null;
			}
		}

		PageHelper.startPage(pageNum, pageSize);
		List<User> list = userDao.queryUserBySearchDto(userSearch);

		List<UserSearchVo> users = Lists.newArrayList();
		PageInfo pageInfo = new PageInfo(list);
		if (CollectionUtils.isNotEmpty(list)) {
			users = buildDetails(list);
		}
		pageInfo.setList(users);
		return pageInfo;
	}

	private List<UserSearchVo> buildDetails(List<User> list) {
		List<Long> uids = Lists.newArrayList();
		for (User user : list) {
			uids.add(user.getUid());
		}
		List<String> infoNames = Lists.newArrayList(UserInfoName.LOCATION.name(), UserInfoName.POSITION.name());
		Map<Long, Map<String, String>> UserInfoMap = userInfoService.findByUidsAndInfoNames(uids, infoNames);
		Set<String> postCodes = Sets.newHashSet();
		for (Long uid : UserInfoMap.keySet()) {
			Map<String, String> map = UserInfoMap.get(uid);
			if(MapUtils.isNotEmpty(map)){
				String cityId = map.get(UserInfoName.LOCATION.name());
				if(StringUtils.isNotBlank(cityId)){
					if(StringUtils.contains(cityId, ",")){
						cityId = StringUtils.substringAfterLast(cityId, ",");
					}
					postCodes.add(cityId);
				}
			}
		}
		Map<String,CityInfo> cityInfoMap = Maps.newHashMap();
		if(CollectionUtils.isNotEmpty(postCodes)){
			List<CityInfo> cityInfos = cityInfoService.selectByListPostCode(Lists.newArrayList(postCodes));
			if(CollectionUtils.isNotEmpty(cityInfos)){
				for(CityInfo cityInfo:cityInfos){
					cityInfoMap.put(cityInfo.getPostcode(), cityInfo);
				}
			}
		}
		
		List<UserSearchVo> vos = Lists.newArrayList();
		for (User user : list) {
			UserSearchVo vo = new UserSearchVo();
			BeanUtils.copyProperties(user, vo);
			if (UserInfoMap.get(user.getUid()) != null) {
				vo.setPosition(UserInfoMap.get(user.getUid()).get(UserInfoName.POSITION.name()));
				String cityId = UserInfoMap.get(user.getUid()).get(UserInfoName.LOCATION.name());
				if (StringUtils.isNotBlank(cityId)) {
					// 根据cityid查询信息
					if (StringUtils.contains(cityId, ",")) {
						cityId = StringUtils.substringAfterLast(cityId, ",");
					}
					CityInfo cityInfo = cityInfoMap.get(cityId);
					if(null != cityInfo){
						if (cityInfo.getTopCityId() == 0) { // 说明是顶级省份
							vo.setGovId(cityInfo.getPostcode());
							vo.setGovName(cityInfo.getCityName());
						} else {
							vo.setCityId(cityInfo.getPostcode());
							vo.setCityName(cityInfo.getCityName());
							vo.setGovId(cityInfo.getPostcode().substring(0, 2) + "0000");
							vo.setGovName(cityInfo.getTopCity());
						}
					}
				}
			}
			vos.add(vo);
		}
		return vos;
	}

	@Override
	public boolean upageStatus(List<Long> ids, String status) {
		boolean ret = true;
		try {
			userDao.upageStatus(ids,status);
		} catch (Exception e) {
			e.printStackTrace();
			ret = false;
		}	
		return ret;
	}

	@Override
	public List<String> findUidByRealNameOrUmobile(String keyWord) {
		
		return this.userDao.findUidByRealNameOrUmobile(keyWord);
	}

	@Override
	public Map<Long, User> findUserMapByUids(List<Long> userIdList) {
		List<User> userList = findByUid(userIdList);
		Map<Long,User> userMap = Maps.newHashMap();
		for(User user:userList){
			userMap.put(user.getUid(), user);
		}
		return userMap;
	}
	
	
	

}
